#!/bin/bash

# Send background click
function back_click()
{
  ps_cxt="$1"
  # Click screen every $sleep_time seconds
  sleep_time=15

  # wait process to loading, max 10x$SHOW_TIME
  wait_cnt=1
  while [ $wait_cnt -le 10 ]
  do
    ps -elf | grep -v 'grep' | grep "$ps_cxt" 1>/dev/null 2>&1
    [ $? -eq 0 ] && break
    sleep $sleep_time
    let wait_cnt=$wait_cnt+1
  done

  # during process lifecycle, click the screen with left button
  while [ 1 -eq 1 ]
  do
    ps -elf | grep -v 'grep' | grep "$ps_cxt" 1>/dev/null 2>&1
    [ $? -ne 0 ] && break
    xdotool click 1
    sleep $sleep_time
  done
}

function kill_firefox(){
  ps -elf | grep -v grep | \
  grep firefox | awk '{print $4}' | \
  xargs kill 2>/dev/null
}


function show_ppt()
{
  ppt_path="$1"
  find "$ppt_path" -regex ".*\.ppt[x]*" | \
  while read fn
  do
    back_click "libreoffice/program/oosplash -show" &
    libreoffice -show "$fn" --norestore
  done
}

function show_url()
{
  url="$1"
  show_time="$2"

  kill_firefox
  firefox "$url" -width 1280 -height 1024 &
#  sleep 10
#  xdotool key F11
  sleep $show_time
  xdotool key ctrl+w
  sleep 3
  kill_firefox
}

function is_work_time()
{
  weekday=`date +"%w"`
  let weekday=$weekday+0
  [ $weekday -eq 0 -a $weekday -eq 6 ] && echo "no" && return
  hour=`date +"%H"`
  let hour=$hour+0
  [ $hour -ge 9 -a $hour -le 19 ] && echo "yes" && return
  echo "no" && return
}

while [ 1 ]
do
  ad_on=`is_work_time`
  if [ "$ad_on"=="yes" ]
  then
    xset dpms force on
    show_ppt "/pbfd/incoming"
    show_url "http://aqicn.org/city/beijing/cn/" 60
  else
    xset dpms force off
    sleep 300
  fi
done


